package com.roc.admin.infrastructure.repository.impl;

import com.roc.admin.domain.entity.OperationLog;
import com.roc.admin.domain.repository.OperationLogRepository;
import com.roc.admin.infrastructure.mapper.OperationLogMapper;
import com.roc.admin.infrastructure.persistence.OperationLogPO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Repository;

/**
 * 操作日志仓储实现类
 */
@Repository
public class OperationLogRepositoryImpl implements OperationLogRepository {

    private final OperationLogMapper operationLogMapper;

    public OperationLogRepositoryImpl(OperationLogMapper operationLogMapper) {
        this.operationLogMapper = operationLogMapper;
    }

    @Override
    public OperationLog save(OperationLog operationLog) {
        OperationLogPO operationLogPO = toOperationLogPO(operationLog);
        if (operationLogPO.getId() == null) {
            operationLogMapper.insert(operationLogPO);
        } else {
            operationLogMapper.updateById(operationLogPO);
        }
        return toOperationLog(operationLogPO);
    }

    /**
     * 将操作日志实体转换为持久化对象
     *
     * @param operationLog 操作日志实体
     * @return 操作日志持久化对象
     */
    private OperationLogPO toOperationLogPO(OperationLog operationLog) {
        if (operationLog == null) {
            return null;
        }
        OperationLogPO operationLogPO = new OperationLogPO();
        BeanUtils.copyProperties(operationLog, operationLogPO);
        return operationLogPO;
    }

    /**
     * 将持久化对象转换为操作日志实体
     *
     * @param operationLogPO 操作日志持久化对象
     * @return 操作日志实体
     */
    private OperationLog toOperationLog(OperationLogPO operationLogPO) {
        if (operationLogPO == null) {
            return null;
        }
        OperationLog operationLog = new OperationLog();
        BeanUtils.copyProperties(operationLogPO, operationLog);
        return operationLog;
    }
}
